package com.wolf.system.controller;

import com.wolf.constant.SessionKey;
import com.wolf.system.model.SysUser;
import com.wolf.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    private static final String SUCCESS_MSG = "success";
    private static final String FAIL_MSG = "fail";

    @Autowired
    private ISysUserService manager;

    /**
     *  跳转客户列表页面
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public ModelAndView loginView(){
        ModelAndView model = new ModelAndView();
        model.setViewName("repair/login");
        return model;
    }

    /**
     * 用户登录
     * @param userName
     * @param userPwd
     * @return
     */
    @RequestMapping(value = "/loginUser")
    @ResponseBody
    public String loginUser(@RequestParam(value = "userName") String userName,
                            @RequestParam(value = "userPwd") String userPwd,
                            @RequestParam(value = "clientCode") String clientCode){
        SysUser sysUser = manager.findSysUser(userName,userPwd);
        if(sysUser == null){
            return FAIL_MSG;
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession(true);
        session.setAttribute(SessionKey.USERINFO.getCode(), sysUser);
        return SUCCESS_MSG;
    }

    /**
     * 用户登出
     * @return
     */
    @RequestMapping(value = "/layout")
    @ResponseBody
    public void layout(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession(true);
        session.invalidate();
    }

}
